import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError} from 'axios';
import { ElMessage } from 'element-plus'
import Router from "@/router";
import Store from "@/store";
const request: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_RES_URL, // API 请求的默认前缀，可根据环境变量自行配置
    timeout: 60000, // 请求超时时间
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    }
});



// 异常拦截处理器
const errorHandler = (error: AxiosError) => {
    ElMessage.error(error.message)
    
    if (error.response) {
        switch (error.response.status) {
        case 401:
          // 登录过期错误处理
        break;
        case 500:
          // 服务器错误处理
        break;
        default:
        }
    }
    return Promise.reject(error);
};

// 将参数转换成功 formdata 接收格式
function stringify (data:any) {
    const formData = new FormData()
    for (const key in data) {
      // eslint-disable-next-line no-prototype-builtins
      if (data.hasOwnProperty(key)) {
        if (data[key]) {
          if (data[key].constructor === Array) {
            if (data[key][0]) {
              if (data[key][0].constructor === Object) {
                formData.append(key, JSON.stringify(data[key]))
              } else {
                data[key].forEach((item:any, index:number) => {
                  formData.append(key + `[${index}]`, item)
                })
              }
            } else {
              formData.append(key + '[]', '')
            }
          } else if (data[key].constructor === Object) {
            formData.append(key, JSON.stringify(data[key]))
          } else {
            formData.append(key, data[key])
          }
        } else {
          if (data[key] === 0) {
            formData.append(key, '0')
          } else {
            formData.append(key, '')
          }
        }
      }
    }
    return formData
  }
// request interceptor
request.interceptors.request.use((config: AxiosRequestConfig) => {
    /**
     * 如果token 存在，则给请求头加token
     */
    // console.log(config)
    //  let formData = new FormData();
    //  config.data = config.data || {}
    //  Object.keys(config.data).forEach(key=>{
    //      formData.append(key, config.data[key]);
    //  })
     config.headers = {
        TOKEN : String(window.localStorage.getItem('token')),
        X_CSRF_TOKEN:Store.getters.CSRF,
     }
    config.data = stringify(config.data)
    return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use((response: AxiosResponse) => {
  if(response.data.code == 'notAuth'){
    Router.push({
      name:'login'
    })
    return
  }  
  if(response.data.result == 'fail') {
        ElMessage.error(response.data.reason)
    }
    
    return response.data;
}, errorHandler);

export default request;

